
class MyBlockingQueue {       // 基于数组的方式实现
    private String[] elems = null;
    private volatile int head = 0; // 头，指向的是第一个元素
    private volatile int tall = 0; // 尾+1，指向的是最后一个元素加1
    private volatile int size = 0; // 有效元素的个数

    public MyBlockingQueue(int capacity) { //构造方法
        elems = new String[capacity];
    }

    void put(String elem) throws InterruptedException { // 添加，入队列
        synchronized (this) {

            if (size >= elem.length()) {
                this.wait();
            }
            elems[tall] = elem;
            tall++;
            if (tall >= elem.length()) {
                tall = 0;
            }
            size++;
            this.notify();
        }
        // 绝大部分都是修改操作，加上锁，更安全
    }

    String take() throws InterruptedException {      // 拿出，出队列
        synchronized (this) {
            if (size == 0) {
                this.wait();     //队列为空时，需要put中wait来唤醒
            }
            String result = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            this.notify(); // 唤醒wait，队列中有元素就唤醒wake获取数据
            return result;
        }
    }
}

// --------------------------- 使用生产着消费者模型
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread t1 = new Thread(() -> {
            int count = 1;
            while (true) {
                try {
                    queue.put(count+"");
//                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产" + count);

                count++;
            }
        });

        Thread t2 = new Thread(()-> {
            try {
                while (true) {
                    String result = queue.take();
                    System.out.println("消费" + result);
                }
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        });
        t1.start();
        Thread.sleep(1000);
        t2.start();
    }
}
